<script setup lang="ts">
import { ref, computed } from 'vue'
import { getHomeBannerAPI } from '@/services/home'
import type { BannerItem } from '@/types/home'
import { onLoad } from '@dcloudio/uni-app'
import type { CategoryTopItem } from '@/types/category'
import { getCategoryTopAPI } from '@/services/category'
import CategorySkeleton from './CategorySkeleton.vue'

// 获取屏幕边界到安全区距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 搜索的值
const seek = ref('')
// 搜索栏是否显示
const isShow = ref(false)
// 搜索输入
const input = () => {
  isShow.value = true
}
// 搜索框获取焦点时
const focus = () => {
  isShow.value = true
}
// 搜索框失去焦点时
const blur = () => {
  isShow.value = false
}

// 声明搜索的商品
interface Good {
  id: number
  name: string
}

// 搜索栏所有商品列表 && 分类列表
const categoryList = ref<CategoryTopItem[]>([])
const searchList = ref<Good[]>([])
const getCategoryTopData = async () => {
  const res = await getCategoryTopAPI()
  // 获取分类列表数据
  categoryList.value = res.result

  // 查询时，过滤出模糊匹配的数据
  const filtered = res.result.filter((v) => v.children)

  // 将数据对象里嵌套的所有商品扁平化处理并返回一个新的数组
  searchList.value = filtered.flatMap((category) =>
    category.children.flatMap((subCategory) =>
      subCategory.goods.map((good) => ({ id: Number(good.id), name: good.name })),
    ),
  )
}

// 过滤出符合条件的商品
const filterList = computed(() => {
  var arr: any[] = []
  // 展示所有搜索商品(商品过多，没必要先展示所有的)
  // searchList.value.forEach((item) => arr.push(item))
  // 展示过滤后的商品
  if (seek.value) {
    arr = searchList.value.filter((item) => item.name.includes(seek.value))
  }
  return arr
})

// 获取轮播图数据
const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI(2)
  bannerList.value = res.result
}

// // 获取分类列表数据
// const categoryList = ref<CategoryTopItem[]>([])
// const getCategoryTopData = async () => {
//   const res = await getCategoryTopAPI()
//   categoryList.value = res.result
// }

// 高亮下标
const activeIndex = ref(0)

// 提取二级分类数据
const subCategoryList = computed(() => {
  return categoryList.value[activeIndex.value]?.children || []
})

// 是否加载完毕
const isFinish = ref(false)

// 加载数据
onLoad(async () => {
  // getHomeBannerData()
  // getCategoryTopData()
  await Promise.all([getHomeBannerData(), getCategoryTopData()])
  isFinish.value = true
})
</script>

<template>
  <view class="viewport" v-if="isFinish">
    <!-- 搜索框 -->
    <view class="search">
      <uni-search-bar
        v-model="seek"
        @input="input"
        @focus="focus"
        @blur="blur"
        placeholder="搜索商品"
        bgColor="#f3f3f3"
        class="easyInput"
        :radius="8"
      >
        <template v-slot:searchIcon>
          <uni-icons color="#595c63" size="18" type="search" />
        </template>
      </uni-search-bar>
      <!-- 搜索栏提示框 -->
      <!-- #ifdef MP-WEIXIN-->
      <view
        class="InputList"
        v-show="isShow && filterList.length"
        :style="{ top: (safeAreaInsets?.top || 0) + 10 + 'px' }"
      >
        <navigator
          v-for="(item, index) in filterList"
          :key="index"
          class="listSon"
          :url="`/pages/goods/goods?id=${item.id}`"
        >
          {{ item.name }}
        </navigator>
      </view>
      <!-- #endif -->
      <!-- #ifdef H5 || APP-PLUS-->
      <view
        class="InputList"
        v-show="isShow && filterList.length"
        :style="{ top: (safeAreaInsets?.top || 0) + 50 + 'px' }"
      >
        <navigator
          v-for="(item, index) in filterList"
          :key="index"
          class="listSon"
          :url="`/pages/goods/goods?id=${item.id}`"
        >
          {{ item.name }}
        </navigator>
      </view>
      <!-- #endif -->
    </view>

    <!-- 分类 -->
    <view class="categories">
      <!-- 左侧：一级分类 -->
      <scroll-view class="primary" scroll-y>
        <view
          v-for="(item, index) in categoryList"
          :key="item.id"
          class="item"
          :class="{ active: index === activeIndex }"
          @tap="activeIndex = index"
        >
          <text class="name"> {{ item.name }} </text>
        </view>
      </scroll-view>
      <!-- 右侧：二级分类 -->
      <scroll-view class="secondary" scroll-y>
        <!-- 轮播图 -->
        <XtxSwiper class="banner" :list="bannerList" />
        <!-- 内容区域 -->
        <view class="panel" v-for="item in subCategoryList" :key="item.id">
          <view class="title">
            <text class="name">{{ item.name }}</text>
            <navigator class="more" hover-class="none">全部</navigator>
          </view>
          <view class="section">
            <navigator
              v-for="goods in item.goods"
              :key="goods.id"
              class="goods"
              hover-class="none"
              :url="`/pages/goods/goods?id=${goods.id}`"
            >
              <image class="image" :src="goods.picture"></image>
              <view class="name ellipsis">{{ goods.name }}</view>
              <view class="price">
                <text class="symbol">¥</text>
                <text class="number">{{ goods.price }}</text>
              </view>
            </navigator>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
  <!-- 骨架屏 -->
  <CategorySkeleton v-else />
</template>

<style lang="scss">
@import './category.scss';
</style>
